#!/bin/bash

# SVN specific:
#---------------
# $Author: simonbaev $
# $LastChangedDate: 2010-02-22 20:19:39 -0500 (Mon, 22 Feb 2010) $
# $Revision: 8 $
#

function enceval {
	subj="$1"
	basenc=$(echo "$subj" | file --mime-encoding - | cut -d" " -f2)
	status="Encoding cannot be identified"
	rcode=1;
	if [ $basenc = "iso-8859-1" ]; then
		for enc in "CP1251" "KOI8-R" "CP866" "ISO-8859-5"; do
			read -p "$(printf "Does '%s' look readable? (y/n): " "$(echo "$subj" | iconv -f "$enc" -t UTF8 -)")"
			if [[ $REPLY = [yY] ]]; then
				status="$enc"
				rcode=0
				break
			fi				
		done
	else
		status=$basenc
		rcode=0
	fi
	echo "$status"
	return "$rcode"
}

function encupdate {
	enc="$1"
	subj="$2"
	key="$3"
	fname="$4"
	if [ ! $enc = "us-ascii" ] && [ ! $enc = "utf-8" ]; then
		subj=$(echo "$subj" | iconv -f $enc -t UTF8 -)
		mp3info -$key "$subj" "$fname"		
	fi
	echo "$subj"
}

firstpass=true
trackid=1
for mp3file in *.mp3; do
	title=$(mp3info -p"%t\n" "$mp3file")
	album=$(mp3info -p"%l\n" "$mp3file")
	artist=$(mp3info -p"%a\n" "$mp3file")
	if [ $firstpass = true ]; then 
		firstpass=false
		albumenc=$(enceval "$album") &&\
		artistenc=$(enceval "$artist")
		if [ $? -ne 0 ]; then
			echo "Error: Either album or artist tag encoding cannot be identified"
			exit 1
		fi	
	fi		
	titlenc=$(enceval "$title")
	if [ $? -eq 0 ]; then
		title=$(encupdate "$titlenc" "$title" "t" "$mp3file")
		album=$(encupdate "$albumenc" "$album" "l" "$mp3file")	
		artist=$(encupdate "$artistenc" "$artist" "a" "$mp3file")				
		if [ -n "$(mp3info -p "%n\n" "$mp3file")" ]; then
			track=$(mp3info -p "%n\n" "$mp3file")
		else
			track=$trackid			
		fi
		newname=$(printf "%02d-%s.mp3\n" "$track" "$title")
		[ "$newname" != "$mp3file" ] && mv "$mp3file" "$newname"
	fi
	((trackid++))
done

